package com.fclassroom.logger.controller;

import com.fclassroom.ErrorCode;
import com.fclassroom.logger.LoggerVar;
import com.fclassroom.logger.entity.LogCache;
import com.fclassroom.logger.entity.OperaterLog;
import com.fclassroom.logger.exception.LoggerException;
import com.fclassroom.logger.service.ILogService;
import com.fclassroom.logger.service.ProducerService;
import com.jason.framework.mvc.spring.BaseController;
import com.jason.framework.util.JsonUtil;
import com.jason.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
/**
 * 日志系统的http接口，可以收发消息。
 * @author jason
 */
@Controller
@RequestMapping("/")
public class LoggerForDBController extends BaseController {
	@Autowired
	private LogCache logCache;
	@Autowired
	private ILogService logService;
 
	/**
	 *记录系统和用户日志,单条上传<br/>
	 *系统日志：ERROR|2015-12-24 18:07:17,900|10|11|1.2.3|org.apache.zookeeper.ClientCnxn$SendThread|readResponse(717)|Got ping response for sessionid: 0x151b43dfc9f006f after 28ms<br/>
	 *用户日志：ERROR|2015-12-23 19:08:38,588|99|admin|192.168.1.1|10|11|113.666.444.333|com.jason.test.KafkaLogTester|main(16)|hello.json|22|200|100|hello world  <br/>
	 * @param msgType 1:用户日志 2:系统日志，
	 * @param msgKey  msg的标识
	 * @param msg     单条日志详情
	 * @return
	 */
	@RequestMapping(value = "/recordByMsg")
	public ResponseEntity<String> recordByMsg(HttpServletRequest request,Integer msgType,String msgKey, String msg){
//		logger.info("进入日志系统！");
		String errorCode=ErrorCode.System_error;
		if(msgType!=null && StringUtil.isNotEmpty(msg)){
			StringTokenizer tokenizer=new StringTokenizer(msg, LoggerVar.log_delim);
			int countTokens=tokenizer.countTokens();
			if(msgType==2 && countTokens!=8){
				return renderData(ErrorCode.Parameter_error);
			}
			if(msgType==1 && countTokens!=15){
				return renderData(ErrorCode.Parameter_error);
			}
			try {
				if(msgType!=null&& msgType==2){
					//系统日志通过logtail
					//logService.insertSystemLog(new SystemLog(msg));
					//logCache.putSystemLog(new SystemLog(msg));
				}else{
					logCache.putOperaterLog(new OperaterLog(msg,getIpAddr(request)));
					//producerService.send(new OperaterLog(msg,getIpAddr(request)));
				}
				errorCode=ErrorCode.Success;
			} catch (LoggerException e) {
				logger.error("recordByMsg Exception,msgKey:"+msgKey+",msg:"+msg,e.getMessage());
			}
		}
		return renderData(errorCode);
	}
	/**
		 *记录系统和用户日志,多条上传<br/>
		 *系统日志：ERROR|2015-12-24 18:07:17,900|10|11|1.2.3|org.apache.zookeeper.ClientCnxn$SendThread|readResponse(717)|Got ping response for sessionid: 0x151b43dfc9f006f after 28ms<br/>
		 *用户日志：ERROR|2015-12-23 19:08:38,588|99|admin|192.168.1.1|10|11|113.666.444.333|com.jason.test.KafkaLogTester|main(16)|hello.json|22|200|100|hello world  <br/>
		 * @param msgType 1:用户日志 2:系统日志，
		 * @param msgKey  msg的标识
		 * @param msgJson 多条日志详情
		 * @return
		 */
		@RequestMapping(value = "/recordByMsgs")
		public ResponseEntity<String> recordByMsgs(HttpServletRequest request,Integer msgType,String msgKey, String msgJson){
			String errorCode=ErrorCode.System_error;
			List<Map<String, Object>> msgList = JsonUtil.jsonToObject(msgJson, List.class);
			String msg="";
			for(Map<String, Object> msgmap:msgList){
				if(msgmap.containsKey("msg")){
					msg=msgmap.get("msg").toString()+LoggerVar.log_delim+msgmap.get("msgContent").toString();
				}else{
					continue;
				}
				if(msgType!=null &&StringUtil.isNotEmpty(msg)){
					StringTokenizer tokenizer=new StringTokenizer(msg, LoggerVar.log_delim);
					int countTokens=tokenizer.countTokens();
					if(msgType==2 && countTokens!=8){
						return renderData(ErrorCode.Parameter_error);
					}
					if(msgType==1 && countTokens!=15){
						return renderData(ErrorCode.Parameter_error);
					}
					try {
						if(msgType!=null&& msgType==2){
							//logService.insertSystemLog(new SystemLog(msg));
							//logCache.putSystemLog(new SystemLog(msg));
						}else{
							//logService.insertOperaterLog(new OperaterLog(msg,getIpAddr(request)));
							//logRows.add(new OperaterLog(msg,getIpAddr(request)));
							logCache.putOperaterLog(new OperaterLog(msg,getIpAddr(request)));
						}
						errorCode=ErrorCode.Success;
					} catch (LoggerException e) {
						logger.error("recordByMsg Exception,msgKey:%s,msg:%s",msgKey,msg);
						errorCode=ErrorCode.System_error;
					}
				}
			}
			return renderData(errorCode);
		}
	/**
	 *记录系统和用户日志,文件方式上传<br/>
	 *系统日志：ERROR|2015-12-24 18:07:17,900|10|11|1.2.3|org.apache.zookeeper.ClientCnxn$SendThread|readResponse(717)|Got ping response for sessionid: 0x151b43dfc9f006f after 28ms<br/>
	 *用户日志：ERROR|2015-12-23 19:08:38,588|99|admin|192.168.1.1|10|11|113.666.444.333|com.jason.test.KafkaLogTester|main(16)|hello.json|22|200|100|hello world  <br/>
	 * @param msgType 1:用户日志 2:系统日志，
	 * @param msgKey  msg的标识
	 * @param file    多条日志，一行一条。 
	 * @return
	 */
	@RequestMapping(value = "/recordByFile")
	public ResponseEntity<String> recordByFile(HttpServletRequest request,
			Integer msgType,String msgKey, @RequestParam(value = "logFile", required = true)MultipartFile file){
		String errorCode=ErrorCode.Success;
		try {
			if(msgType!=null&& msgType==2){
				//TODO 暂时取消系统日志的读写。
			}else{
				BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()));
				String msg = "";
				try {
					while ((msg = br.readLine()) != null) {
						logCache.putOperaterLog(new OperaterLog(msg,getIpAddr(request)));
					}
				} catch (LoggerException | IOException e) {
					logger.error("recordByMsg Exception,msgKey:%s,msg:%s", msg);
				}
				//logService.putFile(relativeFile);

			}
			errorCode=ErrorCode.Success;
		} catch (IllegalStateException | IOException e1) {
			logger.error("解析日志文件出错:"+e1);
		}
		return renderData(errorCode);
	}
	
	/**
	 * @api {get} /getReadAndTurnExamCount.json
	 * @apiDescription 教师获取本月贡献  dou
	 * @apiGroup log
	 * @apiVersion 1.0.1
	 */
	@RequestMapping(value = "/getReadAndTurnExamCount")
	public ResponseEntity<String> getReadAndTurnExamCount(Long accountId){
		if (accountId == null){
			return renderData(ErrorCode.Parameter_error, null);
		}
		Map<String,Integer> res=null;
		try {
			res=logService.getReadAndTurnExamCount(accountId);
		} catch (Exception e) {
			logger.error("教师app获取本月贡献异常"+e.getMessage());
		}
		return renderData(ErrorCode.Success,
				messageSource.getMessage(ErrorCode.Success, null, ErrorCode.Success, null),res);
	}
	
	/**
	 * @api {get} /getLogExamRead.json
	 * @apiDescription 获取读卷日志
	 * @apiParam examId
	 * @apiParam accountId
	 * @apiParam schoolId
	 * @apiGroup log
	 * @apiVersion 1.0.1
	 */
	@RequestMapping(value = "/getLogExamRead")
	public ResponseEntity<String> getLogExamRead(Long examId, Long userId,Long schoolId){
		if (schoolId == null){
			return renderData(ErrorCode.Parameter_error, null);
		}
		return renderData(ErrorCode.Success,
				logService.getLogExamRead(userId, examId, schoolId));
	}
	
	/**
	 * @api {get} /getLogExamReadDetail.json
	 * @apiDescription 获取读卷日志详细
	 * @apiParam examId
	 * @apiGroup log
	 * @apiVersion 1.0.1
	 */
	@RequestMapping(value = "/getLogExamReadDetail")
	public ResponseEntity<String> getLogExamReadDetail(Long logId){
		if (logId == null){
			return renderData(ErrorCode.Parameter_error, null);
		}
		return renderData(ErrorCode.Success, logService.getLogExamReadDetail(logId));
	}
	
	/**
	 * @api {get} /getLogDetails.json
	 * @apiDescription 获取读卷日志详细结构
	 * @apiParam examId
	 * @apiGroup log
	 * @apiVersion 1.0.1
	 */
	@RequestMapping(value = "/getLogDetails")
	public ResponseEntity<String> getLogDetails(Long examId, Long userId,Long schoolId,String startTime,String endTime){
		if (schoolId == null || examId == null){
			return renderData(ErrorCode.Parameter_error, null);
		}
		return renderData(ErrorCode.Success, logService.getLogExamRead(schoolId,examId,userId,startTime,endTime));
	}
	/**
	 * @api {get} /addLogRScaner.json
	 * @apiDescription 获取读卷日志详细
	 * @apiParam userId
	 * @apiParam schoolId
	 * @apiParam model
	 * @apiParam serialNumber
	 * @apiGroup log
	 * @apiVersion 1.0.1
	 */
	@RequestMapping(value = "/saveLogRScanner")
	public ResponseEntity<String> saveLogRScanner(Long userId,Long schoolId,Long scannerId, String model,String serialNumber){
		if (userId == null || schoolId == null || StringUtil.isBlank(model) || StringUtil.isBlank(serialNumber)){
			return renderData(ErrorCode.Parameter_error, null);
		}
		return renderData(ErrorCode.Success, logService.saveLogRScanner(userId,schoolId,scannerId, model,serialNumber));
	}
}
